﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Solution.Data;

namespace Solution.Business.Core
{
    public abstract class abstractCommonDAL<T> : ICommonDAL<T> where T : class
    {
        public NewsMvcEntities DB = new NewsMvcEntities();

        public virtual bool Insert(T pEntity)
        {
            try
            {
                DB.Set<T>().Add(pEntity);
                DB.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }

        }
        public virtual bool Insert(IEnumerable<T> lEntity)
        {
            foreach (var item in lEntity)
            {
                if (!Insert(item))
                    return false;
            }
            return true;
        }
        public virtual bool Delete(T pEntity)
        {
            try
            {
                DB.Set<T>().Remove(pEntity);
                DB.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }

        }
        public virtual T GetOne(int Id)
        {
            return DB.Set<T>().Find(Id);
        }
        public virtual void Attach(T pEntity)
        {
            DB.Set<T>().Attach(pEntity);
        }     
        public virtual void ReLoad(T pEntity)
        {
            DB.Entry<T>(pEntity).Reload();
        }
        public virtual IQueryable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return DB.Set<T>().Where(where);
        }
        public virtual IQueryable<T> GetAll()
        {
            return DB.Set<T>();
        }
        public virtual IQueryable<T> GetAll(bool isDeleted)
        {
            return DB.Set<T>();
        }
        public virtual void SaveChange()
        {
            DB.SaveChanges();
        }

        public bool Update(T pEntity)
        {
            try
            {
                DB.Entry(pEntity).State = EntityState.Modified;
                DB.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
